package com.loveofsoftware.quotes;

import android.app.Activity;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MeditationActivity extends Activity {

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("MODE", mMode);
		outState.putInt("MINUTES", minutes);
		outState.putInt("SECONDS", seconds);
		outState.putLong("START_TIME", startTime);
		outState.putLong("PAUSE_TIME", pauseTime);
		outState.putLong("TIME_PAUSED", timePaused);
		outState.putInt("TOKEN", 1);
	}

	private static final int MODE_STOPPED = 1;
	private static final int MODE_STARTED = 2;
	private static final int MODE_PAUSED = 3;

	int mMode = MODE_STOPPED;

	int minutes = 30;
	int seconds = 0;
	long startTime = -1;
	long pauseTime = -1;
	long timePaused = 0;

	private final Handler mHandler = new Handler();
	private Runnable updateTextView;
	private static final int TIMER_RESOLUTION = 500;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timekeeper);
		if (null != savedInstanceState
				&& 0 != savedInstanceState.getInt("TOKEN")) {
			mMode = savedInstanceState.getInt("MODE");
			minutes = savedInstanceState.getInt("MINUTES");
			seconds = savedInstanceState.getInt("SECONDS");
			startTime = savedInstanceState.getLong("START_TIME");
			pauseTime = savedInstanceState.getLong("PAUSE_TIME");
			timePaused = savedInstanceState.getLong("TIME_PAUSED");
			System.out.println("Retrieved minutes/seconds : " + minutes + ","
					+ seconds);
		}
		setTimeToKeep();
		final TextView textview = (TextView) findViewById(R.id.tvTimeLeft);

		if (null != textview) {

			textview.setTextColor(Color.GREEN);
			textview.setTextSize(64);// 16sp
			textview.setSingleLine(true);

			textview.setOnTouchListener(new View.OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					if (mMode == MODE_STOPPED
							&& event.getAction() == MotionEvent.ACTION_DOWN) {
						toggleNumberPicker();
						return true;
					}
					return false;
				}

			});
		}

		updateTextView = new Runnable() {
			long timeLeft = -1;

			public void run() {
				if (mMode == MODE_STARTED) {
					long timePassed = System.currentTimeMillis() - startTime
							- timePaused;
					System.out.println("startTime/timePassed/timePaused : "
							+ startTime + "," + timePassed + "," + timePaused);
					long timeToKeepMillis = (minutes * 60 + seconds) * 1000;
					;
					timeLeft = timeToKeepMillis - timePassed;
					if (timeLeft < 0) {
						timeLeft = 0;
						done();
					}

					long min = timeLeft / (60 * 1000);
					long sec = timeLeft / 1000 % 60;

					textview.setText("" + min + " : " + sec);
					mHandler.postDelayed(this, TIMER_RESOLUTION);
				}
			}

		};

		Button startStopButton = (Button) findViewById(R.id.StartStopButton);
		if (null != startStopButton) {
			startStopButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					switch (mMode) {
					case MODE_STOPPED:
						start(true);
						break;
					case MODE_STARTED:
					case MODE_PAUSED:
						stop();
						break;
					}
				}
			});
		}

		Button pauseResumeButton = (Button) findViewById(R.id.PauseResumeButton);
		if (null != pauseResumeButton) {
			pauseResumeButton.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					switch (mMode) {
					case MODE_STARTED:
						pause();
						break;
					case MODE_PAUSED:
						resume();
						break;
					}
				}
			});
		}

		switch (mMode) {
		case MODE_STOPPED:
			stop();
			break;
		case MODE_STARTED:
			start(false);
			break;
		}

		final Activity activity = this;

		((ImageView) findViewById(R.id.TibetanBownImageView))
				.setOnTouchListener(new View.OnTouchListener() {

					public boolean onTouch(View arg0, MotionEvent event) {
						if (event.getAction() == MotionEvent.ACTION_DOWN) {
							MediaPlayer mp = MediaPlayer.create(activity,
									R.raw.tinsha);
							mp.start();
						}
						return false;
					}
				});

		NumberPicker picker = (NumberPicker) findViewById(R.id.MinutePicker);
		NumberPicker picker1 = (NumberPicker) findViewById(R.id.SecondsPicker);
		picker.setOnValueChangeListener(new NumberPicker.ValueChangeListener() {

			public void onNumberPickerValueChange(NumberPicker picker, int value) {

				minutes = value;
				setTimeToKeep();
				return;
			}
		});
		picker1
				.setOnValueChangeListener(new NumberPicker.ValueChangeListener() {

					public void onNumberPickerValueChange(NumberPicker picker,
							int value) {

						seconds = value;
						setTimeToKeep();
						return;
					}
				});
		toggleNumberPicker();
	}

	private void setTimeToKeep() {
		if (mMode == MODE_STOPPED)
			((TextView) findViewById(R.id.tvTimeLeft)).setText("" + minutes
					+ " : " + seconds);
	}

	private void done() {
		MediaPlayer mp = MediaPlayer.create(this, R.raw.tinsha);
		mp.start();
		stop();
	}

	private void start(boolean bBtnClicked) {
		if (bBtnClicked) {
			startTime = System.currentTimeMillis();
			mMode = MODE_STARTED;
		}
		timePaused = 0;
		renderState();
		mHandler.postDelayed(updateTextView, TIMER_RESOLUTION);
	}

	private void stop() {
		mMode = MODE_STOPPED;
		renderState();
	}

	private void pause() {
		pauseTime = System.currentTimeMillis();
		mMode = MODE_PAUSED;
		renderState();
	}

	private void resume() {
		timePaused += (System.currentTimeMillis() - pauseTime);
		mMode = MODE_STARTED;
		mHandler.postDelayed(updateTextView, TIMER_RESOLUTION);
		renderState();

	}

	private void renderState() {
		switch (mMode) {
		case MODE_STOPPED:
			((Button) findViewById(R.id.StartStopButton)).setText("Start");
			((Button) findViewById(R.id.PauseResumeButton))
					.setVisibility(View.INVISIBLE);
			break;
		case MODE_STARTED:
			((Button) findViewById(R.id.StartStopButton)).setText("Stop");
			((Button) findViewById(R.id.PauseResumeButton))
					.setVisibility(View.VISIBLE);
			((Button) findViewById(R.id.PauseResumeButton)).setText("Pause");
			break;
		case MODE_PAUSED:
			((Button) findViewById(R.id.PauseResumeButton)).setText("Resume");
			break;
		}
	}

	void toggleNumberPicker() {
		NumberPicker picker = (NumberPicker) findViewById(R.id.MinutePicker);
		NumberPicker picker1 = (NumberPicker) findViewById(R.id.SecondsPicker);
		switch (picker.getVisibility()) {
		case View.VISIBLE:
			picker.setVisibility(View.INVISIBLE);
			picker1.setVisibility(View.INVISIBLE);
			((TextView) findViewById(R.id.tvTimeLeft))
					.setTextColor(Color.GREEN);
			findViewById(R.id.PauseResumeButton).setEnabled(true);
			findViewById(R.id.StartStopButton).setEnabled(true);
			findViewById(R.id.TibetanBownImageView).setEnabled(true);
			break;
		case View.INVISIBLE:
			picker.setVisibility(View.VISIBLE);
			picker1.setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.tvTimeLeft)).setTextColor(Color.GRAY);
			findViewById(R.id.PauseResumeButton).setEnabled(false);
			findViewById(R.id.StartStopButton).setEnabled(false);
			findViewById(R.id.TibetanBownImageView).setEnabled(false);
			break;
		}

		System.out.println("Toggle number picker");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.minimal_menu, menu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exit:
			this.finish();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
}